package com.kele.web.vertx.consumer.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.handler.LoggerHandler;
import io.vertx.servicediscovery.ServiceDiscovery;
import io.vertx.servicediscovery.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConsumRestVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumRestVerticle.class);

    protected ServiceDiscovery discovery;

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        discovery = ServiceDiscovery.create(vertx);

        Router router = Router.router(vertx);
        HttpServerOptions httpServerOptions = new HttpServerOptions().setLogActivity(true);
        vertx.createHttpServer(httpServerOptions)
                .requestHandler(router)
                .listen(8004, "kele.com", res -> {
                    if (res.succeeded()) {
                        LOGGER.info("http 服务启动:{}", res.result());
                    } else {
                        LOGGER.error("HTTP_SERVER START FAILED:", res.cause());
                    }
                });

        router.get("/db2").handler(LoggerHandler.create()).handler(ctx -> {
            System.out.println("订阅接口");
            discovery.getRecord(new JsonObject().put("name", "db"), ar -> {
                if (ar.succeeded() && ar.result() != null) {
                    // Retrieve the service reference
                    ServiceReference reference = discovery.getReference(ar.result());
                    // Retrieve the service object
                    WebClient client = reference.getAs(WebClient.class);
                    // You need to path the complete path
                    client.get("/db").send(res -> {
                        ctx.json(res.result().bodyAsJsonArray());
                        reference.release();
                    });
                }
            });

        });

    }


}
